import { V, Connection, ExpressContext } from 'x-engine';
import { failed, success, returnFloat } from '../../../lib/utils';
import { X } from 'x-orm';
import { MbUserToken } from '../ml/mb_user_token';
import { VrOrder } from '../ml/order';
import { COrderStatus, caipiao } from '../../../collect';
import { PdLog } from '../ml/pd_log';
import { time } from 'locutus/php/datetime';
import { VrPick, VrPickStatus } from '../ml/vr_pick';
import { base64_decode } from 'locutus/php/url';
import { ProxyUser } from '../ml/proxy_user';
import { ProxyMember } from '../ml/proxy_member';
import { Request } from 'express';


@V.Controller({
    type: Connection.HTTP,
    url: '/proxy/api/:method',
    dataType: "json",
    authorization: [
        async (ctx: ExpressContext) => {
            console.log(123)
            let token = ctx.req.body.token || ctx.req.query.token;
            if (!token) {
                ctx.res.send(JSON.stringify(failed()));
                return false;
                // return failed();
            }
            const member = await X.of(MbUserToken).findOne({
                where: {
                    token: token
                },
                addon: {
                    member: true
                }
            });
            if (!member) {
                ctx.res.send(JSON.stringify(failed('no member')));
                return false;
            }
            (ctx as any).member = member;
            return true;
        }
    ]
})
export class FrontApi {
    /**
    * 中奖订单列表
    * @param token 
    * @param type 
    * @param page 
    * @param rows 
    */
    async prize_orders(
        member: MbUserToken,
        type?,
        page?,
        rows?
    ) {
        // if(!token){
        //     return failed();
        // }
        // const member = await X.of(MbUserToken).findOne({
        //     where : {
        //         token : token
        //     },
        //     addon : {
        //         member : true
        //     }
        // });
        // if(!member){
        //     return failed('no member');
        // }
        if (!page) {
            page = 1;
        }
        if (!rows) {
            rows = 20;
        }

        let [orders, count] = await X.of(VrOrder).fetch({
            where: {
                buyer_id: member.member_id,
                caipiao_status: (() => {
                    switch (type) {
                        case 'gotten':
                            return COrderStatus.gotten;
                        case 'saled':
                            return COrderStatus.saled;
                        default:
                            return {
                                eq : COrderStatus.win,
                            }
                    }
                })()
            },
            page: page,
            rows: rows
        });


        return success({
            list: orders,
            total: count
        })
    }



    /**
     * 一键转卖
     */
    async one_key_saled(
        member: MbUserToken,
        order_sn
    ) {
        if (!order_sn) {
            return failed();
        }
        order_sn = order_sn.split(',').map(item => item.trim());
        const orders = await X.of(VrOrder).find({
            where: {
                buyer_id: member.member_id,
                order_sn: {
                    in: order_sn
                },
                caipiao_status: COrderStatus.win
            }
        });
        if (!orders.length) {
            return failed("order not found");
        }

        let flag = await X.transition(async x => {
            for (let order of orders) {
                //更新彩票状态
                order.caipiao_status = COrderStatus.saled;
                await x.of(VrOrder).save(order);
                //给用户增加余额
                let m = member.member;
                let money = returnFloat(((order.order_amount - order.s_fee - order.f_fee) * 2) * 0.98);
                m.available_predeposit = m.available_predeposit - 0 + Number(money);
                await x.save(m);
                //写入日志
                let pd = new PdLog;
                pd.lg_add_time = time();
                pd.lg_member_id = member.member_id;
                pd.lg_member_name = m.member_name;
                pd.lg_admin_name = 'admin';
                pd.lg_type = 'recharge';
                pd.lg_av_amount = money;
                pd.lg_freeze_amount = 0;
                pd.lg_desc = "订单 " + order.order_sn + ' 转卖';
                await x.save(pd);
            }
            return true;

        });
        if (flag) {
            return success();
        }
        else {
            return failed();
        }
    }
    
    async one_key_gotten(
        member: MbUserToken,
        order_sn
    ){
        if (!order_sn) {
            return failed();
        }
        order_sn = order_sn.split(',').map(item => item.trim());
        const orders = await X.of(VrOrder).find({
            where: {
                buyer_id: member.member_id,
                order_sn: {
                    in: order_sn
                },
                caipiao_status: COrderStatus.win
            }
        });
        if (!orders.length) {
            return failed("order not found");
        }

        //提货
        let flag = await X.transition(async x => {
            for(let order of orders){
                //插入数据
                let pick = new VrPick;
                pick.time = time();
                pick.order_id = order.order_id;
                pick.status = VrPickStatus.notdeal;
                pick.code = member.member.member_mobile;
                await x.save(pick);

                order.caipiao_status = COrderStatus.gotten;
                await x.save(order);
            }
            return true;
        });

        if (flag) {
            return success();
        }
        else {
            return failed();
        }
    }


    /**
     * 代理商添加会员
     */
    async addProxyMember(
        req : Request,
        member: MbUserToken, 
        proxy_code,
        wechat_nickname
    ){
        proxy_code = base64_decode(proxy_code);
        if(!proxy_code){
            return failed();
        }
        if(!wechat_nickname){
            return;
        }
        let user = await X.of(ProxyUser).findOne(proxy_code);
        if(!user){
            return failed();
        }
        let m = await X.of(ProxyMember).findOne({
            where : {
                phone : member.member.member_mobile
            }
        });
        if(m){
            return success();
        }
        if(!m){
            m = new ProxyMember;
            m.add_time = time();
            m.nickname = wechat_nickname;
            m.phone = member.member.member_mobile;
            m.parent_id = user.id;
            m.ip = req.ip.replace(/^[^\d]+/,"");
            await X.save(m);
        }
        return success();
    }

    async pd_pay(
        member : MbUserToken,
        order_sn
    ){
        if(!order_sn){
            return failed("param error");
        }
        let m = member.member;
        //检查订单
        let order = await X.of(VrOrder).findOne({
            where :{
                order_sn :order_sn,
                buyer_id :member.member_id,
                order_state : 10
            }
        });
        if(!order){
            return failed("no order");
        }
        if(order.order_amount > m.available_predeposit){
            return failed("no enough money");
        }

        let flag = await X.transition(async x => {
            m.available_predeposit -= order.order_amount;
            await x.save(m);

            order.order_state = 20;
            await x.save(order);

            let pd = new PdLog;
            pd.lg_add_time = time();
            pd.lg_member_id = member.member_id;
            pd.lg_member_name = m.member_name;
            pd.lg_admin_name = 'admin';
            pd.lg_type = 'order_pay';
            pd.lg_av_amount = -order.order_amount;
            pd.lg_freeze_amount = 0;
            pd.lg_desc = "订单 " + order.order_sn + ' 支付';
            await x.save(pd);
            return true;
        });
        if(flag){
            return success();
        }
        else{
            return failed("pay failed");    
        }

    }
}